<?php
namespace App\Admin\Controllers\ZiNiao;

use App\Models\OverSeasIn\Delivery;
use App\Models\ZiNiao\PlansPost;
use Encore\Admin\Controllers\AdminController;
use Illuminate\Support\Facades\Request;
class PlansPostController extends AdminController{

    protected $title = 'RPA计划任务';

    protected $filters = [
        's_date' => null,
        'e_date' => null,
        'planId' => null,
        'name' => null,
        'status' => null,
    ];

    protected function grid()
    {
        $filtersField = array_keys($this->filters);
        $filters = $this->_getFilters($filtersField);
        $this->_initFilters($filters);
        $query = $this->_initQuery($filters);
        $paginator = $this->_paginator($query);
        $action = getAction($filtersField);
        $filtersBlade = [];
        $filtersBlade['s_date'] = $this->filters['s_date'];
        $filtersBlade['e_date'] = $this->filters['e_date'];
        $filtersBlade['planId'] = $this->filters['planId'];
        $filtersBlade['name'] = $this->filters['name'];
        $filtersBlade['status'] = getOptions(PlansPost::$_status,$this->filters['status']);
        return view('ziniao.plans-post.index', compact('paginator','action','filtersBlade'));
    }

    private function _getFilters($filtersField){
        $filters = [];
        foreach ($filtersField as $field){
            $filters[$field] = request($field);
        }
        return $filters;
    }

    private function _initFilters($filters){
        foreach ($filters as $field => $filter){
            $this->filters[$field] = $filter;
        }
    }

    private function _initQuery($filters){
        $query = PlansPost::query()->orderBy('id', 'DESC');
        foreach ($filters as $field => $filter){
            if(!$filter)continue;
            if($field == 's_date'){
                $query->where('s_date','>=',$filter);
            }
            if($field == 'e_date'){
                $query->where('e_date','<=',$filter);
            }
            if(in_array($field,['planId','name','status'])){
                $query->where($field,$filter);
            }
        }
        return $query;
    }

    private function _paginator($query){
        return $query->paginate((int) (request("per_page",20)))->appends(Request::input());
    }
}
